﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Series;
using OxyPlot.WindowsForms;
using OxyPlot.Legends;
using OPCService.Utils;
using MongoDB.Driver;
using OpcItem = OPCService.Model.Item;

namespace OPCService
{
    public partial class HistoryChart : Form
    {
        private PlotModel plotModel;
        private LineSeries dataSeries;
        private LinearAxis yAxis;
        private string cnname;
        private string tagname;
        private string unit;
        private static readonly String colName = ConfigHelper.ReadConfig("colname");
        private MongoDbHelper mongoDbHelper;
        private ToolTip toolTip;
        private double currentMin = double.MaxValue;
        private double currentMax = double.MinValue;

        public HistoryChart(string cn_name = "汽包水位", string tag_name = "Applications.BurningLine3.LRSA_01", string messure= "mm")
        {
            InitializeComponent();
            this.Icon = new Icon("Resource/accs32.ico");
            this.tagname = tag_name;
            this.cnname = cn_name;
            this.unit = messure;
            lblTitle.Text = cnname + "";
            dtStartDate.Value = DateTime.Now.AddHours(-1); ;
            dtEndDate.Value = DateTime.Now;
            mongoDbHelper = new MongoDbHelper();

            InitializeToolTip();
            InitializePlot();
            Task.Run(async () =>
            {
                try
                {
                    await getChartData();
                }
                catch (Exception ex)
                { }
            });
        }

        private void InitializeToolTip()
        {
            toolTip = new ToolTip();
        }

        private void InitializePlot()
        {
            // 创建图表模型
            plotModel = new PlotModel
            {
                //Title = cnname + "历史曲线",
                //Subtitle = "",
                TitleFontSize = 16,
                SubtitleFontSize = 12,
                // 确保边距足够显示图例
                PlotMargins = new OxyThickness(60, 20, 20, 40),
                PlotAreaBorderThickness = new OxyThickness(1, 0, 0, 1) // 添加边框以便查看绘图区域
            };

            // 创建坐标轴
            var xAxis = new DateTimeAxis
            {
                Position = AxisPosition.Bottom,
                StringFormat = "HH:mm", // 自定义时间格式
                Title = "时间",
                MajorGridlineStyle = LineStyle.Solid,
                MinorGridlineStyle = LineStyle.Dot,
                IntervalType = DateTimeIntervalType.Minutes, // 自动选择间隔类型
                Angle = 45 // 旋转标签防止重叠
            };

            string title;
            if (unit != "")
            {
                title = cnname + "（" + unit + "）";
            }
            else
            {
                title = cnname;
            }
            yAxis = new LinearAxis
            {
                Position = AxisPosition.Left,
                Title = title,
                Key = tagname,
                TitleColor = OxyColors.Blue,
                TextColor = OxyColors.Blue
            };

            plotModel.Axes.Add(xAxis);
            plotModel.Axes.Add(yAxis);

            // 创建温度曲线系列
            dataSeries = new LineSeries
            {
                Title = cnname, // 必须设置Title才会显示在图例中
                StrokeThickness = 2,
                Color = OxyColors.Blue,
                YAxisKey = tagname,
                TrackerFormatString = "时间: {2:yyyy-MM-dd HH:mm:ss}\n数值: {4:0.00}\n系列: {0}"// 配置追踪器格式
            };

            // 添加系列到模型
            plotModel.Series.Add(dataSeries);

           /* // 关键：正确添加图例 - 确保图例在可视区域内
            plotModel.Legends.Add(new Legend
            {
                LegendPosition = LegendPosition.RightTop,
                LegendPlacement = LegendPlacement.Outside, // 确保在绘图区域外
                LegendOrientation = LegendOrientation.Vertical,
                LegendBackground = OxyColor.FromArgb(220, 255, 255, 255), // 半透明背景
                LegendBorder = OxyColors.Gray,
                LegendBorderThickness = 1,

                // 确保图例不会太大而超出边界
                LegendMaxWidth = 100,
                LegendMaxHeight = 80
            });*/

            // 设置模型到PlotView
            plotView.Model = plotModel;
            plotView.MouseMove += PlotView_MouseMove;
        }

        private async Task getChartData()
        {
            dataSeries.Points.Clear();
            // 创建构建器
            var builder = Builders<OpcItem>.Filter;

            // 构建排序方式：按 datetime 倒序
            var sort = Builders<OpcItem>.Sort.Descending(x => x.datetime);
            DateTime startDate = dtStartDate.Value;
            DateTime endDate = dtEndDate.Value;
            FilterDefinition<OpcItem> filter = Builders<OpcItem>.Filter.And(
                builder.Eq("tag_name", tagname),
                builder.Gte("datetime", startDate),
                builder.Lte("datetime", endDate)
            );

            List<OpcItem> datalist = mongoDbHelper.findBySort<OpcItem>(colName, filter, sort);
            if (datalist.Count > 0)
            {
                foreach (OpcItem item in datalist)
                {
                    dataSeries.Points.Add(new DataPoint(DateTimeAxis.ToDouble(item.datetime), item.value));
                    currentMin = Math.Min(currentMin, item.value);
                    currentMax = Math.Max(currentMax, item.value);
                }
                yAxis.Minimum = currentMin * 0.9;
                yAxis.Maximum = currentMax * 1.1;

                // 在UI线程上更新数据
                this.Invoke(new Action(() =>
                {
                    // 更新图表
                    plotModel.InvalidatePlot(true);
                }));
            }
        }

        private void PlotView_MouseMove(object sender, MouseEventArgs e)
        {
            // 获取鼠标位置对应的屏幕坐标
            var screenPoint = new ScreenPoint(e.Location.X, e.Location.Y);

            // 获取追踪器结果
            var trackerResult = plotView.Model.Series[0].GetNearestPoint(screenPoint, false);

            if (trackerResult?.Position != null)
            {
                // 将时间戳转换为 DateTime
                DateTime time = DateTime.FromOADate(trackerResult.DataPoint.X);
                double value = trackerResult.DataPoint.Y;

                // 构造提示信息
                string tooltipText = $"时间: {time:yyyy-MM-dd HH:mm:ss}\n数值: {value:F2} " + unit;

                // 显示 ToolTip（鼠标右侧偏移 20 像素）
                toolTip.Show(tooltipText, this, e.Location.X + 20, e.Location.Y);
            }
            else
            {
                // 如果没有找到点，隐藏 ToolTip
                toolTip.Hide(this);
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            Task.Run(async () =>
            {
                try
                {
                    await getChartData();
                }
                catch (Exception ex)
                { }
            });
        }
    }
}
